#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <pthread.h>

void *send_to_service(void *arg) {
    int *fd = (int *)arg;
    char *send_buf = malloc(1024);
    char *recv_buf = malloc(1024);

    while (fgets(send_buf, 1024, stdin) != NULL) {
        send(*fd, send_buf, strlen(send_buf), 0);
        memset(recv_buf, 0, 1024);
        recv(*fd, recv_buf, 1024, 0);
        printf("recv from server: %s\n", recv_buf);
    }

    shutdown(*fd, SHUT_RDWR);
    free(send_buf);
    free(recv_buf);
    printf("service close\n");
    return NULL;
}

int main(int argc, const char *argv[]) {


    // 服务器结构体
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr("192.168.13.66");
    server.sin_port = htons(8888);

    // 客户端结构体，动态获取客户端IP和端口
    struct sockaddr_in client;

    int client_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (client_fd == -1) {
        perror("socket");
        return 1;
    }

    if (bind(client_fd, (struct sockaddr *)&client, sizeof(client)) == -1) {
        perror("bind");
        close(client_fd);
        return 1;
    }

    if (connect(client_fd, (struct sockaddr *)&server, sizeof(server)) == -1) {
        perror("connect");
        close(client_fd);
        return 1;
    }

    // 挂起一个线程
    pthread_t tid;
    if (pthread_create(&tid, NULL, send_to_service, &client_fd) != 0) {
        perror("pthread_create");
        close(client_fd);
        return 1;
    }

    pthread_join(tid, NULL);
    close(client_fd);
    
    return 0;
}
